package com.mapforge.selection;

import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UncheckedCompositeSelection implements Selection {
	private List<Selection> selections;
	private Rectangle boundingRectangle;

	public UncheckedCompositeSelection() {
		selections = new ArrayList<Selection>();
		boundingRectangle = new Rectangle();
	}

	private UncheckedCompositeSelection(UncheckedCompositeSelection selection) {
		selections = new ArrayList<Selection>();
		for (Selection s : selection.selections) {
			this.selections.add(s);
		}
		boundingRectangle = new Rectangle();
	}

	@Override
	public boolean add(Selection other) {
		selections.add(other);
		boundingRectangle.add(other.getBoundingRectangle());
		return true;
	}

	@Override
	public Selection addition(Selection other) {
		Selection s = new UncheckedCompositeSelection(this);
		s.add(other);
		return s;
	}

	@Override
	public void clearSelection() {
		selections.clear();
		boundingRectangle.setFrame(0, 0, 0, 0);
	}

	@Override
	public boolean contains(int x, int y) {
		for (Selection s : selections) {
			if (s.contains(x, y)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Rectangle getBoundingRectangle() {
		return this.boundingRectangle;
	}

	@Override
	public boolean intersect(Selection other) {
		boolean altered = false;
		for (Selection s : selections) {
			if (!altered)
				altered = s.intersect(other);
			else
				s.intersect(other);
		}
		return altered;
	}

	@Override
	public Selection intersection(Selection other) {
		return null;
	}

	@Override
	public boolean intersects(Selection other) {
		for (Selection s : selections) {
			if (s.intersects(other)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean isEmpty() {
		for (Selection s : selections) {
			if (s.isEmpty()) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Iterator<ComparablePoint> iterator() {
		return new MultiSelectionIterator(selections, null);
	}

	@Override
	public Iterator<ComparablePoint> iterator(Rectangle rectangle) {
		return new MultiSelectionIterator(selections, null);
	}

	@Override
	public void setOrigin(int x, int y) {
		for (Selection s : selections) {
			s.setOrigin(x, y);
		}
	}

	@Override
	public boolean subtract(Selection other) {
		boolean altered = false;
		for (Selection s : selections) {
			if (!altered)
				altered = s.subtract(other);
			else
				s.subtract(other);
		}
		return altered;
	}

	@Override
	public Selection subtraction(Selection other) {
		// TODO Auto-generated method stub
		return null;
	}

}
